<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百炼大模型聊天</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
        }
        
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
        }
        
        .chat-container {
            width: 100%;
            max-width: 600px;
            height: 80vh;
            max-height: 600px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .chat-header {
            background: #667eea;
            color: white;
            padding: 15px 20px;
            font-size: 18px;
            font-weight: 600;
            text-align: center;
            border-bottom: 1px solid #e1e5e9;
        }
        
        #chatHeader {
            padding: 0;
            background-color: transparent;
            border-bottom: none;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
        }
        
        #chatHeader h2 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }
        
        .model-selector {
            display: flex;
            gap: 10px;
        }
        
        .model-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background-color: #fff;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s ease;
            font-size: 14px;
        }
        
        .model-btn.active {
            background-color: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }
        
        .model-btn:hover:not(.active) {
            background-color: #f5f5f5;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8fafc;
        }
        
        .message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
        }
        
        .message.user {
            align-items: flex-end;
        }
        
        .message.ai {
            align-items: flex-start;
        }
        
        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.4;
        }
        
        .message.user .message-content {
            background: #667eea;
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .message.ai .message-content {
            background: white;
            color: #333;
            border: 1px solid #e1e5e9;
            border-bottom-left-radius: 5px;
        }
        
        /* 正在输入的提示样式 */
        .typing-indicator {
            display: flex;
            align-items: center;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            margin: 0 2px;
            background-color: #666;
            border-radius: 50%;
            display: inline-block;
            animation: typing 1.4s infinite ease-in-out both;
        }
        
        .typing-dot:nth-child(1) {
            animation-delay: 0s;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing {
            0% {
                transform: scale(0);
            }
            50% {
                transform: scale(1);
            }
            100% {
                transform: scale(0);
            }
        }
        
        .message-time {
            font-size: 12px;
            color: #94a3b8;
            margin-top: 5px;
        }
        
        .chat-input {
            padding: 15px 20px;
            background: white;
            border-top: 1px solid #e1e5e9;
            display: flex;
            gap: 10px;
        }
        
        #messageInput {
            flex: 1;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }
        
        #messageInput:focus {
            border-color: #667eea;
        }
        
        #sendButton {
            padding: 12px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background 0.3s;
        }
        
        #sendButton:hover {
            background: #5a67d8;
        }
        
        #sendButton:disabled {
            background: #a0aec0;
            cursor: not-allowed;
        }
        
        .typing-indicator {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            margin-bottom: 15px;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            background: #667eea;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-5px);
            }
        }
        
        /* 响应式设计 */
        @media (max-width: 600px) {
            body {
                padding: 0;
                height: 100vh;
            }
            
            .chat-container {
                height: 100vh;
                max-height: none;
                border-radius: 0;
            }
            
            .message-content {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
                <div id="chatHeader">
                    <h2>AI对话助手</h2>
                    <div class="model-selector">
                        <button id="bailianModelBtn" class="model-btn active">百炼模型</button>
                        <button id="deepseekModelBtn" class="model-btn">DeepSeek模型</button>
                    </div>
                </div>
            </div>
        <div class="chat-messages" id="chatMessages">
            <!-- 欢迎消息 -->
            <div class="message ai">
                <div class="message-content">你好！我是百炼大模型，很高兴为你提供帮助。有什么我可以为你解答的吗？</div>
                <div class="message-time">刚刚</div>
            </div>
        </div>
        <div class="chat-input">
            <input type="text" id="messageInput" placeholder="输入消息..." autocomplete="off">
            <button id="sendButton">发送</button>
        </div>
    </div>

    <script>
        const chatMessages = document.getElementById('chatMessages');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        let chatSessionId = null;
        let currentModel = 'bailian'; // 默认使用百炼模型
        
        // 添加消息到聊天界面
        function addMessage(content, isUser = false) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', isUser ? 'user' : 'ai');
            
            const contentDiv = document.createElement('div');
            contentDiv.classList.add('message-content');
            contentDiv.textContent = content;
            
            const timeDiv = document.createElement('div');
            timeDiv.classList.add('message-time');
            timeDiv.textContent = getCurrentTime();
            
            messageDiv.appendChild(contentDiv);
            messageDiv.appendChild(timeDiv);
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            const hours = now.getHours().toString().padStart(2, '0');
            const minutes = now.getMinutes().toString().padStart(2, '0');
            return `${hours}:${minutes}`;
        }
        
        // 显示正在输入的提示
        function showTypingIndicator() {
            const typingDiv = document.createElement('div');
            typingDiv.classList.add('message', 'ai', 'typing-indicator');
            typingDiv.id = 'typingIndicator';
            
            const contentDiv = document.createElement('div');
            contentDiv.classList.add('message-content');
            
            for (let i = 0; i < 3; i++) {
                const dot = document.createElement('span');
                dot.classList.add('typing-dot');
                contentDiv.appendChild(dot);
            }
            
            typingDiv.appendChild(contentDiv);
            chatMessages.appendChild(typingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 隐藏正在输入的提示
        function hideTypingIndicator() {
            const typingIndicator = document.getElementById('typingIndicator');
            if (typingIndicator) {
                chatMessages.removeChild(typingIndicator);
            }
        }
        
        // 创建新的聊天会话
        async function createChatSession() {
            try {
                const response = await fetch('/chat/session/create');
                if (!response.ok) {
                    throw new Error(`创建会话失败: ${response.status}`);
                }
                const sessionData = await response.json();
                chatSessionId = sessionData.id;
                console.log('创建新会话:', chatSessionId);
            } catch (error) {
                console.error('创建会话错误:', error);
                // 如果创建会话失败，仍然允许用户发送消息，但不会保持上下文
                chatSessionId = 'default-session';
            }
        }
        
        // 发送消息到服务器
        async function sendMessage(message) {
            if (!message.trim()) return;
            
            // 如果没有会话ID，创建一个
            if (!chatSessionId) {
                await createChatSession();
            }
            
            // 添加用户消息
            addMessage(message, true);
            messageInput.value = '';
            
            // 禁用发送按钮
            sendButton.disabled = true;
            
            // 显示正在输入的提示
            showTypingIndicator();
            
            try {
                // 调用多轮对话接口
                const endpoint = currentModel === 'bailian' 
                    ? `/chat/bailian/history?sessionId=${encodeURIComponent(chatSessionId)}&message=${encodeURIComponent(message)}`
                    : `/chat/deepseek/history?sessionId=${encodeURIComponent(chatSessionId)}&message=${encodeURIComponent(message)}`;
                
                const response = await fetch(endpoint);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                const responseData = await response.json();
                
                // 隐藏正在输入的提示
                hideTypingIndicator();
                
                // 解析JSON响应，提取content部分
                let aiResponseText = responseData;
                if (typeof responseData === 'object' && responseData.choices && responseData.choices[0] && responseData.choices[0].message && responseData.choices[0].message.content) {
                    aiResponseText = responseData.choices[0].message.content;
                }
                
                // 添加AI回复
                addMessage(aiResponseText, false);
                
            } catch (error) {
                console.error('发送消息失败:', error);
                
                // 隐藏正在输入的提示
                hideTypingIndicator();
                
                // 显示错误消息
                addMessage('抱歉，我暂时无法回答你的问题。请稍后再试。', false);
            } finally {
                // 启用发送按钮
                sendButton.disabled = false;
            }
        }
        
        // 切换模型
        function switchModel(model) {
            currentModel = model;
            chatSessionId = null; // 切换模型时重置会话
            createChatSession();
            
            // 清空聊天记录
            chatMessages.innerHTML = '';
            addMessage(`已切换到${model === 'bailian' ? '百炼' : 'DeepSeek'}模型。你好！我是${model === 'bailian' ? '百炼' : 'DeepSeek'}大模型，很高兴为你提供帮助。有什么我可以为你解答的吗？`, false);
        }
        
        // 事件监听器
        sendButton.addEventListener('click', () => {
            sendMessage(messageInput.value);
        });
        
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage(messageInput.value);
            }
        });
        
        // 窗口加载完成后自动聚焦到输入框并创建会话
        window.addEventListener('load', () => {
            createChatSession();
            messageInput.focus();
            
            // 绑定模型切换按钮事件
            document.getElementById('bailianModelBtn').addEventListener('click', () => {
                switchModel('bailian');
                document.getElementById('bailianModelBtn').classList.add('active');
                document.getElementById('deepseekModelBtn').classList.remove('active');
            });
            
            document.getElementById('deepseekModelBtn').addEventListener('click', () => {
                switchModel('deepseek');
                document.getElementById('deepseekModelBtn').classList.add('active');
                document.getElementById('bailianModelBtn').classList.remove('active');
            });
        });
    </script>
</body>
</html>